/**
 * 销售退货入库单-选择销售出库单界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Sale.SRSelectWSBillForm", {
  extend: "PSI.AFX.Form.EditForm",

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      header: {
        title: me.formatTitle("选择要退货的销售出库单"),
        height: 40
      },
      width: 1200,
      height: 600,
      layout: "border",
      items: [{
        region: "center",
        border: 0,
        bodyPadding: 10,
        layout: "border",
        items: [{
          region: "north",
          height: "50%",
          split: true,
          layout: "fit",
          border: 0,
          items: [me.getWSBillGrid()]
        }, {
          region: "center",
          layout: "fit",
          border: 0,
          items: [me.getDetailGrid()]
        }]
      }, {
        region: "north",
        border: 0,
        layout: {
          type: "table",
          columns: 4
        },
        height: 65,
        bodyPadding: 10,
        items: [{
          id: me.buildId(me, "editWSRef"),
          xtype: "textfield",
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "销售出库单单号"
        }, {
          xtype: "psi_customerfield",
          showModal: true,
          id: me.buildId(me, "editWSCustomer"),
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "客户",
          labelWidth: 60,
          width: 200
        }, {
          id: me.buildId(me, "editFromDT"),
          xtype: "datefield",
          format: "Y-m-d",
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "业务日期（起）"
        }, {
          id: me.buildId(me, "editToDT"),
          xtype: "datefield",
          format: "Y-m-d",
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "业务日期（止）"
        }, {
          xtype: "psi_warehousefield",
          showModal: true,
          id: me.buildId(me, "editWSWarehouse"),
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "仓库"
        }, {
          id: me.buildId(me, "editWSSN"),
          xtype: "textfield",
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "序列号",
          labelWidth: 60,
          width: 200
        }, {
          xtype: "container",
          items: [{
            xtype: "button",
            text: "查询",
            ...PSI.Const.BTN_STYLE,
            width: 100,
            margin: "0 0 0 10",
            iconCls: "PSI-button-refresh",
            handler: me._onQuery,
            scope: me
          }, {
            xtype: "button",
            text: "清空查询条件",
            ...PSI.Const.BTN_STYLE,
            width: 100,
            margin: "0, 0, 0, 10",
            handler: me._onClearQuery,
            scope: me
          }]
        }]
      }],
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      },
      buttons: [{
        text: "选择",
        ...PSI.Const.BTN_STYLE,
        iconCls: "PSI-button-ok",
        formBind: true,
        handler: me._onOK,
        scope: me
      }, {
        text: "取消",
        ...PSI.Const.BTN_STYLE,
        handler() {
          me.close();
        },
        scope: me
      }]
    });

    me.callParent(arguments);

    me.editWSRef = PCL.getCmp(me.buildId(me, "editWSRef"));
    me.editWSCustomer = PCL.getCmp(me.buildId(me, "editWSCustomer"));
    me.editWSWarehouse = PCL.getCmp(me.buildId(me, "editWSWarehouse"));
    me.editFromDT = PCL.getCmp(me.buildId(me, "editFromDT"));
    me.editToDT = PCL.getCmp(me.buildId(me, "editToDT"));
    me.editWSSN = PCL.getCmp(me.buildId(me, "editWSSN"));

    me.pagingToobar = PCL.getCmp(me.buildId(me, "pagingToobar"));
    me.comboCountPerPage = PCL.getCmp(me.buildId(me, "comboCountPerPage"));
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMap.disable();
    }
  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMap.enable();
    }
  },

  /**
   * @private
   */
  _onOK() {
    const me = this;

    const item = me.getWSBillGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择销售出库单");
      return;
    }

    const wsBill = item[0];
    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm.getWSBillInfo.apply(parentForm, [wsBill.get("id")]);
    }

    me.close();
  },

  /**
   * @private
   */
  getWSBillGrid() {
    const me = this;

    if (me._wsBillGrid) {
      return me._wsBillGrid;
    }

    const modelName = me.buildModelName(me, "SRSelectForm");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "ref", "bizDate", "customerName",
        "warehouseName", "inputUserName", "bizUserName",
        "amount", "tax", "moneyWithTax"]
    });
    const storeWSBill = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 20,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0001/SaleRej/selectWSBillList"),
        reader: {
          root: 'dataList',
          totalProperty: 'totalCount'
        }
      }
    });
    storeWSBill.on("beforeload", () => {
      storeWSBill.proxy.extraParams = me.getQueryParam();
    });

    me._wsBillGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      columnLines: true,
      columns: [PCL.create("PCL.grid.RowNumberer", {
        text: "#",
        width: 50
      }), {
        header: "单号",
        dataIndex: "ref",
        width: 120,
        menuDisabled: true,
        sortable: false
      }, {
        header: "业务日期",
        dataIndex: "bizDate",
        menuDisabled: true,
        sortable: false,
        width: 90,
        align: "center"
      }, {
        header: "客户",
        dataIndex: "customerName",
        width: 200,
        menuDisabled: true,
        sortable: false
      }, {
        header: "销售金额(不含税)",
        dataIndex: "amount",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 130
      }, {
        header: "税金",
        dataIndex: "tax",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 90
      }, {
        header: "价税合计",
        dataIndex: "moneyWithTax",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 90
      }, {
        header: "出库仓库",
        dataIndex: "warehouseName",
        menuDisabled: true,
        sortable: false,
        width: 150
      }, {
        header: "业务员",
        dataIndex: "bizUserName",
        menuDisabled: true,
        sortable: false
      }, {
        header: "制单人",
        dataIndex: "inputUserName",
        menuDisabled: true,
        sortable: false
      }],
      listeners: {
        select: {
          fn: me._onMainGridSelect,
          scope: me
        },
        itemdblclick: {
          fn: me._onOK,
          scope: me
        }
      },
      store: storeWSBill,
      tbar: ["->", {
        id: me.buildId(me, "pagingToobar"),
        xtype: "pagingtoolbar",
        border: 0,
        store: storeWSBill
      }, "-", {
          xtype: "displayfield",
          value: "每页显示"
        }, {
          id: me.buildId(me, "comboCountPerPage"),
          xtype: "combobox",
          editable: false,
          width: 60,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["text"],
            data: [["20"], ["50"], ["100"], ["300"],
            ["1000"]]
          }),
          value: 20,
          listeners: {
            change: {
              fn() {
                storeWSBill.pageSize = me.comboCountPerPage.getValue();
                storeWSBill.currentPage = 1;
                me.pagingToobar.doRefresh();
              },
              scope: me
            }
          }
        }, {
          xtype: "displayfield",
          value: "条记录"
        }]
    });

    return me._wsBillGrid;
  },

  /**
   * @private
   */
  _onQuery() {
    const me = this;
    me.pagingToobar.doRefresh();
  },

  /**
   * @private
   */
  getQueryParam() {
    const me = this;

    const result = {};

    const ref = me.editWSRef.getValue();
    if (ref) {
      result.ref = ref;
    }

    const customerId = me.editWSCustomer.getIdValue();
    if (customerId) {
      result.customerId = customerId;
    }

    const warehouseId = me.editWSWarehouse.getIdValue();
    if (warehouseId) {
      result.warehouseId = warehouseId;
    }

    const fromDT = me.editFromDT.getValue();
    if (fromDT) {
      result.fromDT = PCL.Date.format(fromDT, "Y-m-d");
    }

    const toDT = me.editToDT.getValue();
    if (toDT) {
      result.toDT = PCL.Date.format(toDT, "Y-m-d");
    }

    const sn = me.editWSSN.getValue();
    if (sn) {
      result.sn = sn;
    }

    return result;
  },

  /**
   * @private
   */
  _onClearQuery() {
    const me = this;

    me.editWSRef.setValue(null);
    me.editWSCustomer.clearIdValue();
    me.editWSWarehouse.clearIdValue();
    me.editFromDT.setValue(null);
    me.editToDT.setValue(null);
    me.editWSSN.setValue(null);

    me._onQuery();
  },

  /**
   * @private
   */
  getDetailGrid() {
    const me = this;

    if (me._detailGrid) {
      return me._detailGrid;
    }

    const modelName = me.buildModelName(me, "WSBillDetail");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "goodsCode", "goodsName", "goodsSpec",
        "unitName", "goodsCount", "goodsMoney",
        "goodsPrice", "sn", "memo", "taxRate", "tax",
        "moneyWithTax", "goodsPriceWithTax", "rejGoodsCount", "realGoodsCount"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._detailGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      viewConfig: {
        enableTextSelection: true
      },
      title: "销售出库单明细",
      columnLines: true,
      columns: [PCL.create("PCL.grid.RowNumberer", {
        text: "#",
        width: 50
      }), {
        header: "商品编码",
        dataIndex: "goodsCode",
        menuDisabled: true,
        sortable: false
      }, {
        header: "品名/规格型号",
        dataIndex: "goodsName",
        menuDisabled: true,
        sortable: false,
        width: 330,
        renderer(value, metaData, record) {
          return record.get("goodsName") + " " + record.get("goodsSpec");
        }
      }, {
        header: "数量",
        dataIndex: "goodsCount",
        menuDisabled: true,
        sortable: false,
        align: "right",
        width: 90
      }, {
        header: "退货数量",
        width: 90,
        dataIndex: "rejGoodsCount",
        menuDisabled: true,
        sortable: false,
        align: "right"
      }, {
        header: "实际出库数量",
        width: 90,
        dataIndex: "realGoodsCount",
        menuDisabled: true,
        sortable: false,
        align: "right"
      }, {
        header: "单位",
        dataIndex: "unitName",
        menuDisabled: true,
        sortable: false,
        width: 60,
        align: "center"
      }, {
        header: "单价(不含税)",
        dataIndex: "goodsPrice",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 90
      }, {
        header: "销售金额(不含税)",
        dataIndex: "goodsMoney",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 110
      }, {
        header: "税率(%)",
        dataIndex: "taxRate",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        format: "#",
        width: 60
      }, {
        header: "税金",
        dataIndex: "tax",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 90
      }, {
        header: "价税合计",
        dataIndex: "moneyWithTax",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 90
      }, {
        header: "含税价",
        dataIndex: "goodsPriceWithTax",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 90
      }, {
        header: "序列号",
        dataIndex: "sn",
        menuDisabled: true,
        sortable: false
      }, {
        header: "备注",
        dataIndex: "memo",
        width: 200,
        menuDisabled: true,
        sortable: false
      }],
      store: store
    });

    return me._detailGrid;
  },

  /**
   * @private
   */
  _onMainGridSelect() {
    const me = this;
    me.getDetailGrid().setTitle("销售出库单明细");

    me.refreshDetailGrid();
  },

  /**
   * @private
   */
  refreshDetailGrid() {
    const me = this;
    me.getDetailGrid().setTitle("销售出库单明细");
    let grid = me.getWSBillGrid();
    const item = grid.getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const bill = item[0];

    grid = me.getDetailGrid();
    grid.setTitle("单号: " + bill.get("ref") + " 客户: "
      + bill.get("customerName") + " 出库仓库: "
      + bill.get("warehouseName"));
    const el = grid.getEl();
    el?.mask(PSI.Const.LOADING);

    const r = {
      url: me.URL("SLN0001/SaleRej/wsBillDetailListForSRBill"),
      params: {
        billId: bill.get("id")
      },
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
        }

        el?.unmask();
      }
    };

    me.ajax(r);
  }
});
